package com.study.jsl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.google.common.collect.Lists;
import com.study.jsl.ReplyDemo.DataStruct.PageDTO;
import com.study.jsl.ReplyDemo.DataStruct.RdTO;
import com.vladsch.flexmark.html2md.converter.FlexmarkHtmlConverter;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhuzi
 * 2024/10/4 12:43
 */
@Slf4j
public class ReplyDemo {
    static String cookie = "kbz_newcookie=1; Hm_lvt_164fe01b1433a19b507595a43bf58262=1730453326,1730469900,1730643718,1730769335; kbzw__user_login=7Obd08_P1ebax9aX8crr2-CspJmcndHV7Ojg6N7bwNOMsNmmrZepltquq5zf0KySrcSrsNitkdLFqquqnN7N3cOXnKTs3Ny_zYynraqhsKOYnaOiy9XQo5KnlKSwrpqun7CDsY7MuNHVjL3Q7uLh1dqbrJCmgZ_E1NvK3tXj7N2kmbXl1tvNl8TU24G_tJTRlZqpy6iX1Zigl7To0dzGy97XtOLgppepmKWqqZiJu6nIxsGVmdjgzduBvtzW49CZgbfh59jm0aaTqZGlp6Goj6CBx9rbyuvVppepmKWqqZim1MijqqiZp5ylkqSR; kbzw__Session=ohbf2bab1tsugfbfevj0ao62a7";
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");

    @Test
    public void reply() {
        //ArrayList<PageDTO> page = getPage("79364", "201", 0, 25);
        ArrayList<PageDTO> page = getPage("36969", "201", 0, 15);
        //System.out.println(page);
        for (PageDTO pageDTO : page) {
            parsePage(pageDTO);
        }

        Map<String, List<PageDTO>> map = page.stream().filter(i -> StringUtils.isNotBlank(i.getReply())).collect(Collectors.groupingBy(PageDTO::getTitle));

        ArrayList<String> strList = Lists.newArrayList();
        //不计算文章发布日期了,按照最后一个回复当作发布日期
        ArrayList<@Nullable RdTO> rdTOList = Lists.newArrayList();
        map.forEach((k, v) -> {

            RdTO rdTO = new RdTO();
            rdTO.setTitle(k);

            System.out.println(k);
            v.sort((a, b) -> new CompareToBuilder().append(b.getPDt(), a.getPDt()).toComparison());
            rdTO.setReplyList(v);
            rdTO.setTDt(v.get(0).getPDt());
            rdTOList.add(rdTO);
            //String md = PageDTO.md(v);
            //strList.add(md);
        });
        rdTOList.sort((a, b) -> new CompareToBuilder().append(b.getTDt(), a.getTDt()).toComparison());
        rdTOList.forEach(r -> {
            String md = PageDTO.md(r.getReplyList());
            strList.add(md);
        });


        FileUtil.writeLines(strList, "/Users/zhuzi/Downloads/sql/安全饕/guest2.md", StandardCharsets.UTF_8);
    }


    public static void parsePage(PageDTO pageDTO) {
        HttpRequest get = HttpUtil.createGet(pageDTO.getUrl());

        get.cookie(cookie);
        String body = get.execute().body();

        Document rot = Jsoup.parse(body);
        Elements select = rot.select(".markitup-box");

        try {
            Element element = select.get(select.size() - 1);
            pageDTO.setReply(element.html());
        } catch (Exception e) {
            log.error("文章在维护中无法查看 {}", pageDTO.getUrl());
        }
    }

    public static ArrayList<PageDTO> getPage(String uid, String action, int pageStart, int pageEnd) {
        String url = "https://www.jisilu.cn/people/ajax/user_actions/uid-{}__actions-{}__page-{}";

        ArrayList<PageDTO> list = Lists.newArrayList();
        for (int i = pageStart; i <= pageEnd; i++) {
            String urlFormat = StrUtil.format(url, uid, action, i);

            HttpRequest get = HttpUtil.createGet(urlFormat);

            get.cookie(cookie);
            String body = get.execute().body();

            if (StringUtils.isBlank(body)) {
                break;
            }

            Document root = Jsoup.parse(body);
            Elements eleAll = root.getElementsByClass("aw-mod");
            for (Element ele : eleAll) {
                /**
                 * <div class="aw-mod">
                 *  <div class="aw-mod-head">
                 *   <h4 class="aw-hide-txt"><a target="_blank" href="https://www.jisilu.cn/question/488424?show_all_answer-TRUE__item_id-4960275__answer_id-4960275__single-TRUE#!answer_4960275">百股等仓网格之2024年</a></h4>
                 *  </div>
                 *  <div class="aw-mod-body">
                 *   <a href="https://www.jisilu.cn/question/488424" class="aw-border-radius-5 aw-user-center-count">12</a>
                 *   <p class="aw-hide-txt">@vittata &gt; 年初净值1.2288 &gt; 2024/9/20 净值1.0916，本年收益 -11.16% 很不错了，今年最好的沪深300 也跌了6.7%，中证500、1000、2000就跌了17%、24%、28%。更别提跌了44%的北证50...</p>
                 *   <p class="aw-text-color-999">2024-09-20 17:28</p>
                 *  </div>
                 * </div>
                 */
                Elements title = ele.select("div.aw-mod-head > h4 > a");
                PageDTO pageDTO = new PageDTO();


                pageDTO.setTitle(title.text());
                pageDTO.setUrl(title.attr("href"));


                Elements likeEle = ele.select("div.aw-mod-body > a");
                pageDTO.setLike(parseInt(likeEle.text()));

                Elements pdEle = ele.select("div.aw-mod-body > p.aw-text-color-999");
                DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");

                try {
                    LocalDateTime parse = LocalDateTime.parse(pdEle.text(), fmt);
                    pageDTO.setPDt(parse);
                    list.add(pageDTO);
                } catch (Exception e) {
                }
            }
        }

        return list;
    }

    public static int parseInt(String str) {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {

        }
        return 0;
    }

    public interface DataStruct {
        @Data
        @Accessors(chain = true)
        class PageDTO {
            private String title;
            private int like;

            private String url;

            private String reply;

            private LocalDateTime pDt;

            private LocalDateTime firstDt;

            public static String md(List<PageDTO> list) {

                PageDTO pageDTO = list.get(0);
                String collect = list.stream().map(i -> StrUtil.format("## [👍{}]{}\n{}\n\n", i.getLike(), i.getPDt().toString("yyyy-MM-dd HH:mm"), html2Md(i.getReply()))).collect(Collectors.joining("\n"));
                return StrUtil.format("# 🚩{} \n" + "{}\n" + "---\n", pageDTO.getTitle(), collect);
            }
        }

        @Data
        @Accessors(chain = true)
        class RdTO {
            private String title;
            private LocalDateTime tDt;
            private List<PageDTO> replyList;
        }
    }


    public static String html2Md(String html) {
        FlexmarkHtmlConverter converter = FlexmarkHtmlConverter.builder().build();
        String convert = converter.convert(html);
        List<String> split = StrUtil.split(convert, "\n");

        String collect = split.stream().map(item -> {
            if (!StrUtil.startWith(item, ">") && StringUtils.isNotBlank(item)) {
                item = "\n" + item;
            }
            return item;
        }).collect(Collectors.joining("\n"));
        return collect;
    }
}
